import os
from multiprocessing import Process
from typing import List, Tuple, Dict, Any
from processing.calibration import (
    captureCalibrationImages,
    runCalibration,
    runStereoCalibration,
    saveCalibration,
)


class CalibrateCommand:
    def __init__(self, shared_state: Dict[str, Any]):
        """初始化 CalibrateCommand"""
        self._shared_state = shared_state

    def execute(self, args):
        """执行相机校准命令"""
        chessboard_size = (args.rows, args.cols)
        num_images = args.num_images

        # 在这里获取图像路径或采集图像
        if args.use_local:
            # 使用本地图片进行标定
            left_image_paths = [
                f"./images/calib_left_image_{id}.png" for id in range(1, num_images + 1)
            ]
            right_image_paths = [
                f"./images/calib_right_image_{id}.png"
                for id in range(1, num_images + 1)
            ]
        else:
            # 采集实时图像进行标定
            left_image_paths, right_image_paths = captureCalibrationImages(
                self._shared_state, num_images
            )

        process = Process(
            target=runCalibration,
            args=(
                chessboard_size,
                num_images,
                left_image_paths,
                right_image_paths,
            ),
        )
        process.start()
        process.join()


class StereoCalibrateCommand:
    def __init__(self, shared_state: Dict[str, Any]):
        """初始化 StereoCalibrateCommand"""
        self._shared_state = shared_state

    def execute(self, args: Any = None) -> None:
        """执行双目相机标定命令"""
        chessboard_size = (args.rows, args.cols)
        num_images = args.n
        image_size = None

        if args.use_local:
            # 使用本地图片进行标定
            left_image_paths = [
                f"./images/calib_left_image_{id}.png" for id in range(1, num_images + 1)
            ]
            right_image_paths = [
                f"./images/calib_right_image_{id}.png"
                for id in range(1, num_images + 1)
            ]
        else:
            # 采集实时图像进行标定
            left_image_paths, right_image_paths, image_size = captureCalibrationImages(
                self._shared_state, num_images
            )

        process = Process(
            target=runStereoCalibration,
            args=(
                chessboard_size,
                num_images,
                left_image_paths,
                right_image_paths,
                image_size,
            ),
        )
        process.start()
        process.join()
